package com.example.walled_houses.houseTest;

import cn.hutool.json.JSONUtil;
import com.example.walled_houses.dto.HouseDTO;
import com.example.walled_houses.entity.House;
import com.example.walled_houses.service.HouseService;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@SpringBootTest
public class HouseEs {

    @Resource
    private HouseService houseService;

    private RestHighLevelClient client;

    @Test
    void test(){
        House house = houseService.getById(1);
        System.out.println(house.getHousePicture());
    }

    @Test
    void selectHouse() throws IOException{
        Gson gson = new Gson();
        //查询酒店数据
        House house = houseService.getById(1);
        String housePicture = house.getHousePicture();
//        Object fromJson = gson.fromJson(housePicture, new TypeToken<List<String>>() {
//        }.getType());
        List<String> photoUrl = gson.fromJson(housePicture, new TypeToken<List<String>>() {
        }.getType());
        house.setPhotoList(photoUrl);
        HouseDTO houseDTO = new HouseDTO(house);
        //1.准备request对象
        IndexRequest request = new IndexRequest("house").id(house.getHouseId().toString());
        //2.准备json文档
        request.source(JSONUtil.toJsonStr(houseDTO), XContentType.JSON);
        //3.发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://124.223.177.21:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

}
